import { BASE_URL_MAP } from '../config/http.config';

const BASE_URL = () => {
  // 获取小程序账号信息来判断版本类型
  //TODO -区分是正式版，还是体验版
  // const accountInfo = uni.getAccountInfoSync();
  // const envVersion = accountInfo.miniProgram.envVersion;
  const envVersion = 'release';

  if (envVersion === 'release') {
    return BASE_URL_MAP.prod; // 正式版使用生产环境
  } else {
    return BASE_URL_MAP.test; // 开发版和体验版使用测试环境
  }
};

/**
 * 网络请求封装 for uniapp
 */

interface RequestOptions<U = any> {
  url: string;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  data?: U;
  header?: Record<string, string>;
  timeout?: number;
}

function request<T = any, U = any>(options: RequestOptions<U>): Promise<T> {
  const base = BASE_URL();
  const fullUrl = base + options.url;
  console.log('发起网络请求:', {
    url: fullUrl,
    method: options.method || 'GET',
    data: options.data,
  });

  return new Promise((resolve, reject) => {
    // 读取本地 token 和 userId
    const token = uni.getStorageSync('token') as string;
    const userId = uni.getStorageSync('userId') as string;

    uni.request({
      url: base + options.url,
      method: options.method || 'GET',
      data: (options.data as U) || {},
      header: {
        'Content-Type': 'application/json',
        ...(token ? { 'x-token': token } : {}),
        ...(userId ? { 'x-user-id': userId } : {}),
        ...(options.header || {}),
      },
      timeout: options.timeout || 10000,
      success: res => {
        console.log('网络请求成功:', {
          url: fullUrl,
          statusCode: res.statusCode,
          data: res.data,
        });

        if (res.statusCode === 200) {
          resolve(res.data as T);
        } else if (res.statusCode === 401) {
          // 401未登录处理
          console.log('检测到401未登录状态，清除本地存储并跳转到登录页');

          // 防止重复跳转：检查当前是否已经在登录页
          const pages = getCurrentPages();
          const currentPage = pages[pages.length - 1];
          const currentRoute = currentPage ? currentPage.route : '';

          if (currentRoute !== 'pages/login/index') {
            // 清除本地存储的用户信息
            uni.removeStorageSync('token');
            uni.removeStorageSync('userInfo');
            uni.removeStorageSync('expiresAt');

            // 显示未登录提示
            uni.showToast({
              title: '登录已过期，请重新登录',
              icon: 'none',
              duration: 1000,
            });

            // 延迟跳转到登录页，让用户看到提示
            setTimeout(() => {
              uni.reLaunch({
                url: '/pages/login/index',
              });
            }, 1000);
          }

          reject({ statusCode: 401, message: '未登录' });
        } else {
          console.error('请求状态码异常:', res.statusCode, res);
          reject(res);
        }
      },
      fail: err => {
        console.error('网络请求失败:', {
          url: fullUrl,
          error: err,
        });
        reject(err);
      },
    });
  });
}

// 常用方法封装
export function get<T = any, U = any>(url: string, data?: U, header?: Record<string, string>) {
  return request<T>({ url, method: 'GET', data, header });
}

export function post<T = any, U = any>(url: string, data?: U, header?: Record<string, string>) {
  return request<T>({ url, method: 'POST', data, header });
}

export function put<T = any, U = any>(url: string, data?: U, header?: Record<string, string>) {
  return request<T>({ url, method: 'PUT', data, header });
}

// 开发环境下的测试工具：模拟401响应
export function test401Response() {
  console.log('🧪 测试401未登录逻辑...');
  return new Promise((resolve, reject) => {
    // 触发success回调来测试401处理逻辑
    setTimeout(() => {
      // 这里直接调用我们的401处理逻辑
      console.log('检测到401未登录状态，清除本地存储并跳转到登录页');

      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const currentRoute = currentPage ? currentPage.route : '';

      if (currentRoute !== 'pages/login/index') {
        uni.removeStorageSync('token');
        uni.removeStorageSync('userInfo');
        uni.removeStorageSync('expiresAt');

        uni.showToast({
          title: '登录已过期，请重新登录',
          icon: 'none',
          duration: 1000,
        });

        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/login/index',
          });
        }, 1000);
      }

      reject({ statusCode: 401, message: '未登录' });
    }, 100);
  });
}

export default request;
